//
//  AddCarViewController.m
//  PrintPort
//
//  Created by 华谕 on 2017/11/15.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "AddCarViewController.h"
#import "ValuePickerView.h"
#import "BankModel.h"

static int seconds = 60;//计时60s
@interface AddCarViewController ()<UITextFieldDelegate>
{
    UIView *backView;
    UITextField *nameField;
    UITextField *carNumField;
    UITextField *shenFNumField;
    UITextField *phoneField;
    UITextField *codeField;
    UIButton *codeBtn;
    NSTimer *timer;
    
}
@property (nonatomic, strong) ValuePickerView *pickerView;
@property (nonatomic, strong)NSArray *titleAry;
@property (nonatomic, strong)NSArray *pladerAry;
@property (nonatomic, strong)NSArray *bankAry;
@property (nonatomic, strong)BankModel *bankModel;
@property (nonatomic, strong)UILabel *bankNameLab;

@end

@implementation AddCarViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jianpanhuishou:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    //    [timer invalidate];
    [self renewTimer];
    timer = nil;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.pickerView = [[ValuePickerView alloc]init];
    [self requestBankList];
    _titleAry = @[@"持卡人姓名",@"银行卡号",@"身份证号码",@"选择银行",@"预留手机号",@"验证码"];
    _pladerAry = @[@"请输入姓名",@"请输入银行卡号(请绑定储蓄卡)",@"请输入身份证号码",@"",@"请输入手机号",@"请输入验证码"];
    [self creatUI];
}

- (void)creatUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"银行卡";
    self.navigationController.navigationBar.translucent = NO;
    backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    backView.backgroundColor = BacksColor;
    [self.view addSubview:backView];
    CGFloat H = 0;
    for (int i = 0; i < _titleAry.count; i++)
    {
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, H, SCREEN_WIDTH, 50*displaywidth)];
        whiteView.backgroundColor = [UIColor whiteColor];
        [backView addSubview:whiteView];
        UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, 100*displaywidth, 40*displaywidth) Font:13.0 Text:_titleAry[i] Color:RGB(77, 77, 77)];
        [whiteView addSubview:titLab];
        UITextField *textfield = [ZCControl createTextFieldWithFrame:CGRectMake(115*displaywidth, 5*displaywidth, SCREEN_WIDTH-130*displaywidth, 40*displaywidth) placeholder:_pladerAry[i] passWord:NO leftImageView:nil rightImageView:nil Font:13.0];
        [textfield setValue:RGB(179, 179, 179) forKeyPath:@"_placeholderLabel.textColor"];
        textfield.textColor = RGB(77, 77, 77);
        textfield.delegate = self;
        textfield.textAlignment = NSTextAlignmentRight;
        [whiteView addSubview:textfield];
        H+= 50*displaywidth;
        if (i == 3)
        {
            H+=15*displaywidth;
        }
        if (i != 3 && i != 5)
        {
            UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 49*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
            lineview.backgroundColor = LinesColor;
            [whiteView addSubview:lineview];
        }
        if (i == 0)
        {
            nameField = textfield;
        }
        else if (i == 1)
        {
            textfield.keyboardType = UIKeyboardTypeNumberPad;
            carNumField = textfield;
        }
        else if (i == 2)
        {
            shenFNumField = textfield;
        }
        else if (i == 3)
        {
            [textfield removeFromSuperview];
            UILabel *bankLab = [ZCControl createLabelWithFrame:CGRectMake(115*displaywidth, 5*displaywidth, SCREEN_WIDTH-145*displaywidth, 40*displaywidth) Font:13.0 Text:@"" Color:RGB(77, 77, 77)];
            bankLab.textAlignment = NSTextAlignmentRight;
            [whiteView addSubview:bankLab];
            _bankNameLab = bankLab;
            UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH- 30*displaywidth, 17.5*displaywidth, 15*displaywidth, 15*displaywidth) ImageName:@"gs_icon05"];
            imgView.contentMode = UIViewContentModeScaleAspectFit;
            [whiteView addSubview:imgView];
            UIButton *closeBankBtn = [ZCControl createButtonWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50*displaywidth) ImageName:nil Target:self Action:@selector(closeBankAction) Title:nil Font:12.0];
            closeBankBtn.backgroundColor = [UIColor clearColor];
            [whiteView addSubview:closeBankBtn];
            
        }
        else if (i == 4)
        {
            textfield.keyboardType = UIKeyboardTypeNumberPad;
            phoneField = textfield;
        }
        else
        {
            textfield.keyboardType = UIKeyboardTypeNumberPad;
            textfield.frame = CGRectMake(115*displaywidth, 5*displaywidth, SCREEN_WIDTH-250*displaywidth, 40*displaywidth);
            codeField = textfield;
            UIView *lines = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-121*displaywidth, 0, 1*displaywidth, 50*displaywidth)];
            lines.backgroundColor = LinesColor;
            [whiteView addSubview:lines];
            codeBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-120*displaywidth, 0, 120*displaywidth, 50*displaywidth) ImageName:nil Target:self Action:@selector(verifiBtnAction:) Title:@"获取验证码" Font:13.0];
            [codeBtn setTitleColor:RGB(101, 101, 101) forState:UIControlStateNormal];
            codeBtn.backgroundColor = [UIColor whiteColor];
            [whiteView addSubview:codeBtn];
        }
    }
    UIButton *addCarBtn = [ZCControl createButtonWithFrame:CGRectMake(60*displaywidth , H+60*displaywidth, SCREEN_WIDTH-120*displaywidth, 40*displaywidth) ImageName:nil Target:self Action:@selector(soureCarBtnAction) Title:@"确定" Font:15.0];
    [addCarBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addCarBtn.backgroundColor = ThemeColor;
    [addCarBtn.layer setMasksToBounds:YES];
    [addCarBtn.layer setCornerRadius:5*displaywidth];
    [backView addSubview:addCarBtn];
}

- (void)closeBankAction
{
    if (_bankAry.count > 0)
    {
        NSMutableArray *nameAry = [NSMutableArray arrayWithCapacity:0];
        for (BankModel *model in _bankAry)
        {
            NSString *name = model.name;
            [nameAry addObject:name];
        }
        self.pickerView.dataSource = nameAry;
        self.pickerView.pickerTitle = @"选择银行";
        __weak typeof(self) weakSelf = self;
        self.pickerView.valueDidSelect = ^(NSString *value){
            NSArray * stateArr = [value componentsSeparatedByString:@"/"];
            weakSelf.bankNameLab.text = stateArr[0];
            NSInteger index = [stateArr[1] integerValue];
            weakSelf.bankModel = weakSelf.bankAry[index-1];
        };
        [self.pickerView show];
    }
    else
    {
        [self requestBankList];
    }
    
}

- (void)soureCarBtnAction
{
    [self.view endEditing:YES];
    if (nameField.text.length < 1)
    {
        [LTools showMBProgressWithText:@"请输入姓名" addToView:self.view];
        return;
    }
    if (carNumField.text.length < 1)
    {
        [LTools showMBProgressWithText:@"请输入银行卡号" addToView:self.view];
        return;
    }
    if (shenFNumField.text.length < 1)
    {
        [LTools showMBProgressWithText:@"请输入身份证号码" addToView:self.view];
        return;
    }
    if (_bankNameLab.text.length < 1)
    {
        [LTools showMBProgressWithText:@"请选择银行" addToView:self.view];
        return;
    }
    if (phoneField.text.length < 1)
    {
        [LTools showMBProgressWithText:@"请输入手机号" addToView:self.view];
        return;
    }
    if (phoneField.text.length != 11)
    {
        [LTools showMBProgressWithText:@"请输入正确的手机号" addToView:self.view];
        return;
    }
    if (codeField.text.length < 1)
    {
        [LTools showMBProgressWithText:@"请输入验证码" addToView:self.view];
        return;
    }
    [self soureAction];
}

- (void)verifiBtnAction:(UIButton *)btn
{
    [self.view endEditing:YES];
    if (phoneField.text.length < 1)
    {
        [LTools showMBProgressWithText:@"请输入手机号" addToView:self.view];
        return;
    }
    if (phoneField.text.length != 11)
    {
        [LTools showMBProgressWithText:@"请输入正确的手机号" addToView:self.view];
        return;
    }
    [self requestRegisCode4register];
    
}

//验证码
- (void)requestRegisCode4register
{
    [self.view endEditing:YES];
    WEAKSELF;
    NSDictionary *dic = @{@"phone":phoneField.text};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestCodeBankCardParmers:dic Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             [LTools showMBProgressWithText:@"验证码已发送" addToView:weakSelf.view];
             [weakSelf startTimer];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

//确认
- (void)soureAction
{
    NSDictionary *dic = @{@"bankId":_bankModel.ID,
                          @"bank":_bankModel.name,
                          @"cardNum":carNumField.text,
                          @"idCardNum":shenFNumField.text,
                          @"phone":phoneField.text,
                          @"linkman":nameField.text,
                          @"code":codeField.text
                          };
    WEAKSELF;
    [HYBaseHandler requestAddBankCarParmers:dic Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             [LTools showMBProgressWithText:@"添加成功" addToView:sharedDelegate.window];
             if (weakSelf.isTixian)
             {
                 if (weakSelf.addBlock != nil)
                 {
                     BankModel *bankModel = [BankModel mj_objectWithKeyValues:obj[@"data"]];
                     weakSelf.addBlock(bankModel);
                 }
                 
             }
             [weakSelf.navigationController popViewControllerAnimated:YES];
             
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
         
     } failed:^(NSError *error) {
         
     }];
}


- (void)requestBankList
{
    WEAKSELF;
    [HYBaseHandler requestBankListParmers:nil Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             weakSelf.bankAry = [BankModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
         
     } failed:^(NSError *error) {
         
     }];
}

- (void)startTimer
{
    seconds = 60;
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(calculateTime) userInfo:Nil repeats:YES];
    codeBtn.userInteractionEnabled = NO;
}
//计算时间
- (void)calculateTime
{
    NSString *title = [NSString stringWithFormat:@"(%dS)重新获取",seconds];
    codeBtn.titleLabel.text = title;
    [codeBtn setTitle:title forState:UIControlStateNormal];
    
    if (seconds != 0) {
        seconds --;
    }else
    {
        [self renewTimer];
    }
    
}
//计时器归零
- (void)renewTimer
{
    [timer invalidate];//计时器停止
    codeBtn.userInteractionEnabled = YES;
    [codeBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
    seconds = 60;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == codeField || textField == phoneField)
    {
        backView.frame = CGRectMake(0, -80*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT);
        
    }
}

- (void)scrollTap:(id)sender
{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView
{
    [self.view endEditing:YES];
}

- (void)jianpanhuishou:(NSNotification *)notification
{
    backView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
